// 导入工具类函数
const utils = require('../../../utils/util');
let app = getApp()
const db = wx.cloud.database({
  env: app.globalData.CLOUD_ENV
})
const DBScore = db.collection('db_score');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    lists: []
  },

   // 获取成绩列表
   async getScoreFn(openid) {
    wx.showLoading({
      title: '正在加载...',
    })
    let res = await DBScore.where({openid}).count()
    let count = res.total;
    let all = [];
    for(let i = 0 ; i < count ; i+= 20){
      await DBScore.where({openid}).skip(i).get()
        .then(
          content => {
            let {data} = content;
            if(data.length!=0){
              let arr = data.map(item=> {
                let obj = {...item}
                let date = item.create_time && new Date(item.create_time)
                obj.create_time =item.create_time && utils.formatTime(date)
                return obj;
              })
              all = all.concat(arr)
            }
          }
        )
    }
    wx.hideLoading();
    // console.log(all)
    // 记录所有成绩
    this.setData({
      lists: all
    })
    // console.log('1:',this.data.lists)
  },
  // 删除成绩
  removeFn(e){
    let _id = e.currentTarget.dataset.id
    let _openid = wx.getStorageSync('openid')
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除该成绩吗?',
      complete: (res) => {
        if (res.cancel) {
          
        }
        if (res.confirm) {
          DBScore.doc(_id).remove().then(
            content=>{
                // console.log('content',content)
                let {errMsg} = content;
                if(errMsg == "document.remove:ok") {
                    let arr = that.data.lists;
                    let newArr = arr.filter(item=> {
                      if(item._id != _id){
                        return item 
                      }
                    })
                    // console.log(newArr)
                    that.setData({
                      lists: newArr
                    })
                }
                else {
                  wx.showToast({
                    title: '删除成绩失败。',
                    icon: 'none'
                  })
                }
            }
          )
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let openid = wx.getStorageSync('openid')
    if(openid){
      this.getScoreFn(openid)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})